package com.example.docking.service.impl;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.request.MoTaskBillRequest;
import com.example.docking.dao.jindie.response.MaterialEntity;
import com.example.docking.dao.jindie.response.MoTaskbillData;
import com.example.docking.dao.jindie.response.MoTaskbillDetailData;
import com.example.docking.dao.jindie.response.SaveData;
import com.example.docking.dao.jindie.response.motaskbill.SubMaterialEntity;
import com.example.docking.dao.jingxin.request.MaterialtaskDao;
import com.example.docking.dao.jingxin.request.MoTaskbillDao;
import com.example.docking.dao.jingxin.request.SubMaterialDao;
import com.example.docking.service.AuxInfoService;
import com.example.docking.service.MoTaskbillService;
import com.example.docking.util.Constants;
import com.example.docking.util.OrderNumberGenerator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MoTaskbillServiceImpl extends BaseServiceImpl implements MoTaskbillService {
    private static final Logger logger = LoggerFactory.getLogger(MoTaskbillServiceImpl.class);

    /**
     * @ClassName InsertMoTaskbillByJX
     * @Description 需求：从敬信获取数据存入金蝶 生产任务工单
     * @Author zhanghuiping
     * @Date 2025 - 04 - 09 02:08:48
     */
    @Override
    public ResponseData InsertMoTaskbillByJX(DataServiceImpl Service, MoTaskbillDao moTaskbillDao) throws Exception {
        Gson gson = new Gson();
        logger.info("Insert MoTaskbillByJX敬信的生产工单数据：" + gson.toJson(moTaskbillDao));
        ResponseData<SaveData> responseData = new ResponseData<>();

        MoTaskBillRequest moTaskBillRequest = new MoTaskBillRequest();
        moTaskBillRequest.setId(moTaskbillDao.getId());
        moTaskBillRequest.setRemark(moTaskbillDao.getRemark());
        moTaskBillRequest.setBill_no(moTaskbillDao.getTask_no());//生产任务单号
        String empName = moTaskbillDao.getEmp();//计划员
        List<MaterialtaskDao> materials = moTaskbillDao.getMaterials();
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        ApiResult MoTaskbillResult1 = null;
        try {
            EmpServiceImpl empService = new EmpServiceImpl();
            String emp_id = empService.getEmpId(Service, empName);
            moTaskBillRequest.setEmp_id(emp_id);
            //查询部门 获取部门id 默认给定第一个
            DepartmentServiceImpl departmentService = new DepartmentServiceImpl();
            String depart_id = departmentService.getDepartId(Service, "");
            //敬信没有生产车间信息传输 默认给定
            moTaskBillRequest.setDept_id(depart_id);
            //插入商品信息
            List<MaterialEntity> materialList = new ArrayList<>();
            // 调用获取商品数据 数据
            MaterialServiceImpl materialService = new MaterialServiceImpl();
            List<MaterialtaskDao> resultMaterial = materialService.getMaterial(Service, materials);

            for (MaterialtaskDao materialtask : resultMaterial) {
                MaterialEntity materialEntity = new MaterialEntity();
                materialEntity.setMaterial_id(materialtask.getMaterialid());//商品编码
                materialEntity.setQty(materialtask.getMaterialNumber());//数量
                materialEntity.setUnit_id(materialtask.getUnitid());//单位id
                materialEntity.setPlan_commit_date(materialtask.getPlan_commit_date());//计划开工日期
                materialEntity.setPlan_finish_date(materialtask.getPlan_finish_date());//计划完工日期
                List<SubMaterialDao> subMaterial = materialService.insertMaterialSub(Service, materialtask.getSubMaterial());
                List<SubMaterialEntity> subMaterialEntityList = new ArrayList<>();
                for (SubMaterialDao subMaterialDao : subMaterial) {
                    SubMaterialEntity subMaterialEntity = new SubMaterialEntity();
                    subMaterialEntity.setDen_qty_scrap(subMaterialDao.getDen_qty_scrap());
                    subMaterialEntity.setNum_qty_scrap(subMaterialDao.getNum_qty_scrap());
                    subMaterialEntity.setSub_material_id(subMaterialDao.getSub_material_id());//查询商品编码
                    subMaterialEntity.setSub_qty(subMaterialDao.getSub_qty());
                    subMaterialEntity.setSub_unit_id(subMaterialDao.getSub_unit_id());
                    subMaterialEntityList.add(subMaterialEntity);
                }
                materialEntity.setSub_material_entity(subMaterialEntityList);
                materialList.add(materialEntity);
            }
            moTaskBillRequest.setMaterial_entity(materialList);
            //敬信没有单据标签 默认 给定
//            List <MulBillLabel>
            //敬信没有业务类型 默认给定第一个
            AuxInfoService auxInfoService = new AuxInfoServiceImpl();
            String transtypeid = auxInfoService.getTransTypeId(Service, "");
            moTaskBillRequest.setTrans_type_id(transtypeid);

            Date currentDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(currentDate);
            moTaskBillRequest.setBill_date(formattedDate);//当前日期为单据日期
            MoTaskbillResult1 = Service.InsertDataOne(Constants.MO_TASK_BILL, map, moTaskBillRequest);
            Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
            }.getType();
            logger.info("执行插入生产任务单");

            responseData = gson.fromJson(MoTaskbillResult1.getBody(), SaveDataType);

            if (responseData.getErrcode() == 0) {
                logger.info("插入生产任务单成功");
                logger.info("Code: {}", responseData.getErrcode());
                logger.info("Message: {}", responseData.getDescription());
                logger.info("data: {}", responseData.getData());
            } else {
                logger.info("插入生产任务单失败：" + responseData.getErrcode() + responseData.getDescription());
            }
        } catch (com.google.gson.JsonSyntaxException e) {
            responseData.setErrcode(10003);
            responseData.setDescription("JSON解析失败");
            logger.error("JSON解析失败", e);
        } catch (Exception e) {
            responseData.setErrcode(10002);
            responseData.setDescription("运行时异常");
            logger.error("运行时异常", e);
        }
        return responseData;
    }

    /**
     * @MethodName InsertMoTaskbillByCRM
     * @Parameters
     * @Author zhanghuiping
     * @Date 2025 - 04 - 09 02:15:01
     */
    @Override
    public ResponseData InsertMoTaskbillByCrm(DataServiceImpl Service, MoTaskbillDao moTaskbillDao) throws Exception {
        return null;
    }

    /**
     * @MethodName InsertMoTaskbillByERP
     * @Parameters
     * @Author zhanghuiping
     * @Date 2025 - 04 - 09 02:15:07
     */
    @Override
    public ArrayList<MoTaskBillRequest> InsertMoTaskbillByERP(DataServiceImpl Service, ArrayList<MoTaskBillRequest> moTaskBillRequests) throws Exception {
        ResponseData<SaveData> responseData = new ResponseData<>();
        ArrayList<MoTaskBillRequest> ResultMoTaskbillRequests = new ArrayList<>();
        if (moTaskBillRequests.size() == 0) {
            logger.error("没有可以自制的产品");
            responseData.setErrcode(10002);
            responseData.setDescription("没有可以自制的产品，请轮巡");
        }

        for (MoTaskBillRequest moTaskBillRequest : moTaskBillRequests) {
            //单据日期
            Date currentDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(currentDate);
            moTaskBillRequest.setBill_date(formattedDate);//当前日期为单据日期
            //单据编号
            OrderNumberGenerator orderNumberGenerator = new OrderNumberGenerator();
            String orderNumber = orderNumberGenerator.generateOrderNumber();
            moTaskBillRequest.setBill_no(orderNumber);
            //产车间ID 默认值
            DepartmentServiceImpl departmentService = new DepartmentServiceImpl();
            String depart_id = departmentService.getDepartId(Service, "");
            moTaskBillRequest.setDept_id(depart_id);
            //计划员ID
            if (moTaskBillRequest.getEmp_id().equals("")) {
                EmpServiceImpl empService = new EmpServiceImpl();
                String emp_id = empService.getEmpId(Service, "administrator");
                moTaskBillRequest.setEmp_id(emp_id);
            }
            //商品分录 上一步数据已经添加了
            //单据标签 暂无
            //业务类型ID
            AuxInfoService auxInfoService = new AuxInfoServiceImpl();
            String transtypeid = auxInfoService.getTransTypeId(Service, "");
            moTaskBillRequest.setTrans_type_id(transtypeid);
            //保存生产任务单
            ApiResult MoTaskbillResult1 = null;
            Gson gson = new Gson();
            HashMap<String, String> map = new HashMap<>();

            MoTaskbillResult1 = Service.InsertDataOne(Constants.MO_TASK_BILL, map, moTaskBillRequest);
            Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
            }.getType();

            responseData = gson.fromJson(MoTaskbillResult1.getBody(), SaveDataType);
            if (responseData.getErrcode() == 0) {
                moTaskBillRequest.setId(responseData.getData().getIds().get(0));
                ResultMoTaskbillRequests.add(moTaskBillRequest);
                logger.info("插入生产任务单成功");
                logger.info("Code: {}", responseData.getErrcode());
                logger.info("Message: {}", responseData.getDescription());
                logger.info("data: {}", responseData.getData());
            } else {
                logger.error("插入生产任务单失败");
                logger.error("插入生产任务单失败. Errcode: {}, Description: {}", responseData.getErrcode(), responseData.getDescription());
                throw new Exception(responseData.getErrcode() + ":" + responseData.getDescription());
            }
        }
        return ResultMoTaskbillRequests;
    }

    public MoTaskbillData getMoTaskbillDataByBillno(String bill_no) {
        logger.info("根据编号获取生产任务单");
        MoTaskbillData moTaskbillData = new MoTaskbillData();
        HashMap<String, String> map = new HashMap<>();
        map.put("search", bill_no);
        DataServiceImpl Service = new DataServiceImpl();
        Gson gson = new Gson();
        ApiResult DataResult = null;
        try {
            DataResult = Service.SelectDataList(Constants.MO_TASKBILL, map, "");
            Type SaleDataType = new TypeToken<ResponseData<GenericDataItem<MoTaskbillData>>>() {
            }.getType();
            ResponseData<GenericDataItem<MoTaskbillData>> responseSaleData = gson.fromJson(DataResult.getBody(), SaleDataType);
            GenericDataItem<MoTaskbillData> genericDataItem = responseSaleData.getData();
            List<MoTaskbillData> list = genericDataItem.getRows();
            logger.info("根据编号获取生产任务单：code" + responseSaleData.getErrcode());
            logger.info("根据编号获取生产任务单：描述" + responseSaleData.getDescription());
            logger.info("根据编号获取生产任务单：数据" + responseSaleData.getData());
//            System.out.println(responseSaleData.getData());
            if (list != null && list.size() > 0) {
                moTaskbillData = list.get(0);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return moTaskbillData;
    }

    public ResponseData insertBYTran(MoTaskBillRequest moTaskBillRequest) {
        logger.info("insertBYTran插入生产任务单");
        ResponseData respData = null;
        HashMap<String, String> map = new HashMap<>();
        DataServiceImpl Service = new DataServiceImpl();
        Gson gson = new Gson();
        ApiResult MoTaskbillResult1 = null;
        try {
            MoTaskbillResult1 = Service.InsertDataOne(Constants.MO_TASK_BILL, map, moTaskBillRequest);
            Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
            }.getType();


            respData = gson.fromJson(MoTaskbillResult1.getBody(), SaveDataType);

            if (respData.getErrcode() == 0) {
                logger.info("insertBYTran 插入生产任务单成功");
                logger.info("Code: {}", respData.getErrcode());
                logger.info("Message: {}", respData.getDescription());
                logger.info("data: {}", respData.getData());
            } else {
                logger.info("insertBYTran 插入生产任务单失败：" + respData.getErrcode() + respData.getDescription());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        logger.info("执行插入生产任务单");
        return respData;
    }

    public static void main(String[] args) {
        MoTaskbillServiceImpl Service = new MoTaskbillServiceImpl();
        try {
            MoTaskbillData moTaskbillData = Service.getMoTaskbillDataByBillno("SCRW-20250421-00002");
            System.out.println(moTaskbillData.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public MoTaskbillDetailData getMoTaskbillDetaillByBillno(String id) {
        logger.info("根据编号获取生产任务单");
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        DataServiceImpl Service = new DataServiceImpl();
        Gson gson = new Gson();
        ApiResult DataResult = null;
        MoTaskbillDetailData genericDataItem = null;

        if (id == null || id.equals("")) {
            return genericDataItem;
        }

        try {
            DataResult = Service.SelectDataList(Constants.MO_TASKBILL_DETAIL, map, "");
            Type SaleDataType = new TypeToken<ResponseData<MoTaskbillDetailData>>() {
            }.getType();
            ResponseData<MoTaskbillDetailData> responseSaleData = gson.fromJson(DataResult.getBody(), SaleDataType);
            genericDataItem = responseSaleData.getData();
            logger.info("code" + responseSaleData.getErrcode());
            logger.info("描述" + responseSaleData.getDescription());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return genericDataItem;
    }
}